<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix header-box">
        <span>文章分类</span>
        <el-button type="primary" size="mini" @click="add">添加分类</el-button>
      </div>
      <!-- 文章分类表格 -->
      <el-table
        style="width: 100%"
        border
        stripe
        :data="catelist.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
      >
        <el-table-column
          label="序号"
          width="100"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column
          label="分类名称"
          align="center"
          prop="cate_name"
        ></el-table-column>
        <el-table-column
          label="分类别名"
          align="center"
          prop="cate_alias"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="update(scope.row)"
              >修改</el-button
            >
            <el-button type="danger" size="mini" @click="delcate(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加分类的对话框 -->
    <!-- .sync作用实现双向数据绑定
会在运行时给所在标签绑定 @update:属性名的事件, 把接收到子组件内传来的值赋予给右侧Vue变量
组件内$emit('update:visible', true)
这个update: 是固定的
-->
    <!-- 添加/修改 文章分类的对话框 -->
    <el-dialog
      :title="flag ? '添加文章分类' : '修改文章分类'"
      :visible.sync="addVisible"
      width="35%"
      @close="onDialogClosed('addRef')"
    >
      <!-- 添加的表单 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cate_name">
          <el-input
            v-model="addForm.cate_name"
            minlength="1"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类别名" prop="cate_alias">
          <el-input
            v-model="addForm.cate_alias"
            minlength="1"
            maxlength="15"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('addRef')">{{
            flag ? '添加' : '修改'
          }}</el-button>
          <el-button @click="resetForm('addRef')">重置</el-button>
          <el-button @click="addVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分页区域 -->
    <div class="block" v-show="catelist.length > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="catelist.length"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getCateList,
  addCateList,
  updateCateList,
  delCateList,
} from '@/api/article/index.js'
export default {
  name: 'ArtCate',
  data() {
    return {
      // 文章分类的数据
      catelist: [],
      // 添加分类-对话框是否显示
      addVisible: false,
      addForm: {
        // 添加表单的数据对象
        cate_name: '',
        cate_alias: '',
      },
      flag: true, // 用来判断是添加还是修改 true添加 false修改
      editId: '', // 文章分类的id值
      addRules: {
        // 添加表单的验证规则对象
        cate_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          {
            pattern: /^\S{1,10}$/,
            message: '分类名必须是1-10位的非空字符',
            trigger: 'blur',
          },
        ],
        cate_alias: [
          { required: true, message: '请输入分类别名', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9]{1,15}$/,
            message: '分类别名必须是1-15位的字母数字',
            trigger: 'blur',
          },
        ],
      },
      // 每页显示个数
      pageSize: 5,
      // 当前页数
      pageNum: 1,
    }
  },
  created() {
    this.getcatelist()
  },
  methods: {
    // 展示对话框
    add() {
      this.addVisible = true
      this.flag = true
    },
    // 获取文章分类
    async getcatelist() {
      const { data: res } = await getCateList()
      if (res.code !== 0) return this.$message.error('获取文章分类数据失败!')
      this.catelist = res.data
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.flag) {
            this.addcatelist()
          } else {
            this.updatecate()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 增加文章分类
    async addcatelist() {
      const { data: res } = await addCateList(this.addForm)
      if (res.code !== 0) return this.$message.error('增加文章分类失败!')
      this.$message.success(res.message)
      this.addVisible = false
      this.getcatelist()
    },
    // 给表单对象添加数据
    update(obj) {
      // console.log(obj)
      this.flag = false
      this.addVisible = true
      this.editId = obj.id
      // 设置数据回显
      this.$nextTick(() => {
        // 先让对话框出现, 它绑定空值的对象, 才能resetFields清空用初始空值
        this.addForm.cate_name = obj.cate_name
        this.addForm.cate_alias = obj.cate_alias
      })
      // console.log(this.addForm)
    },
    // 修改文章分类
    async updatecate() {
      const { data: res } = await updateCateList({
        id: this.editId,
        ...this.addForm,
      })
      if (res.code !== 0) return this.$message.error('修改文章分类失败!')
      this.$message.success(res.message)
      this.addVisible = false
      this.getcatelist()
    },
    // 删除文章分类
    delcate(obj) {
      this.$confirm('确定删除该文章分类?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delCateList(obj.id).then(({ data: res }) => {
            if (res.code !== 0) return this.$message.error('删除文章分类失败!')
            this.$message.success(res.message)
            this.getcatelist()
            // 假如总数据有11个 每页五个 把第三页仅有的一个删除了以后 会跳转到第二页 但是不显示内容
            // 解决:删除完之后强制跳转到第一页
            this.pageNum = 1
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 对话框关闭时 重置表单的值
    onDialogClosed(formName) {
      this.$refs[formName].resetFields()
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.pageNum = val
    },
  },
}
</script>

<style lang="less" scoped>
.header-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.block {
  width: 50%;
  margin: 30px auto;
}
</style>
